// 多请求-类似防抖
let loadingTimes = 0;
import { showToastUtil } from '../utils/util'
// ifLoad-是否需要全局加载
export const request = (url, params, methods, ifLoad = true) => {
    loadingBefore(ifLoad)

    return new Promise((resolve, reject) => {
        wx.request({
            header: {
                'content-type': 'application/x-www-form-urlencoded' // post请求需要加此项内容，参数才能被正常接收
            },
            url: finalUrl(url),
            data: params,
            method: methods || 'GET',
            dataType: 'json',
            responseType: 'text',
            success: res => {
                // const { code = 0, msg = "服务器内部错误" } = res.data
                // if (code === -1) {
                //     showToastUtil(msg)
                // }
                resolve(res.data)
            },
            fail: err => {
                reject(err)
            },
            complete: () => {
                loadingFinal(ifLoad)
            }
        })
    })
}
// 判断是否需要跨域，或路径拼接 
const finalUrl = (url) => {
    // 1.proxy = https://api.it120.cc
    const baseUrl = 'https://api.it120.cc'
    const urlSplit = url.split('proxy')
    if (urlSplit.length > 1) {
        return baseUrl + urlSplit[1]
    }
    return url

}
// 全局loading开启
const loadingBefore = (ifLoad) => {
    if (ifLoad) {
        // 请求开始-自增
        loadingTimes++;
        wx.showLoading({
            title: "加载中",
            mask: true,
        });
    }
}
// 全局loading关闭
const loadingFinal = (ifLoad) => {
    if (ifLoad) {
        // 请求结束-自减
        loadingTimes--;
        // 所有请求结束-关闭loading
        if (loadingTimes === 0) {
            wx.hideLoading();
        }
    }
}
// 请求失败-弹框提示
// const failLoading = () => {
//     wx.showToast({
//         title: '请求失败',
//         icon: 'error',
//         image: '',
//         duration: 1500,
//         mask: true
//     });
//     wx.hideToast();
// }